/*
 * @Description: 档案分类列表
 * @Author: Rfan
 * @Date: 2022-05-31 15:25:56
 * @LastEditTime: 2022-06-05 11:26:23
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import { useArchiveClassifyContext } from '../contexts/ArchiveClassifyContext';
import { useFormatMessage } from '@/utils/intlHelpers';
import PaneOperate from './PaneOperate';

import styles from '../styles/classifyDetail.module.scss';
import { IPageQuery } from '@/interfaces/global';
import { arrToTree } from '@/utils';
import AddItemDialog from './dialogs/AddItemDialog';
import EditItemDialog from './dialogs/EditItemDialog';
import { IArchiveClassify } from '@/interfaces/archiveType';

const cx = classNames.bind(styles);

const { Column } = Table;

const ClassifyDetail = (props: any) => {
  const { data } = props;
  const formatMessage = useFormatMessage();
  const { classifyList, getClassifyList, selectItems, setSelectKey, deleteClassifyFunc } =
    useArchiveClassifyContext();
  // 表格加载
  const [loading, setLoading] = useState(false);
  // 总条目数
  const [total, setTotal] = useState(0);
  // 表格请求参数
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  // 新增条目父节点ID
  const [addInfo, setAddInfo] = useState<{ pid?: number }>({});
  // 添加弹窗展示状态
  const [addDialogVisible, setAddDialogVisible] = useState(false);
  // 新增条目父节点ID
  const [editInfo, setEditInfo] = useState({});
  // 添加弹窗展示状态
  const [editDialogVisible, setEditDialogVisible] = useState(false);

  /**
   * @description: 档案类型或版本变化时触发
   */
  useEffect(() => {
    setListQuery((state) => ({
      ...state,
      param: {
        ...state.param,
        ...data
      }
    }));
  }, [data]);

  useEffect(() => {
    setLoading(true);
    if (listQuery) {
      setLoading(false);
      setTotal(0);
      getClassifyList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description: 删除条目
   * @param {any} item 条目数据
   * @return {*}
   */
  const deleteItem = (item: any) => {
    deleteClassifyFunc(item.id);
  };

  // 表格选项相关设置
  const onSelectChange = (selectedKeys: number[]): void => {
    setSelectKey(selectedKeys);
  };

  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  /**
   * @description: 新增同级分类方法
   * @param {number} pid 当前条目的父节点
   */
  const addSameLevelClassify = (pid: number) => {
    setAddInfo({ pid });
    setAddDialogVisible(true);
  };

  /**
   * @description: 新增子分类方法
   * @param {number} id 当前条目的id
   */
  const addSubLevelClassify = (id: number) => {
    setAddInfo({ pid: id });
    setAddDialogVisible(true);
  };

  const editClassify = (info: IArchiveClassify) => {
    setEditInfo(info);
    setEditDialogVisible(true);
  };

  return (
    <div className={cx('classify-detail-pane')}>
      <PaneOperate />
      <div className={cx('container')}>
        <Table
          dataSource={arrToTree(classifyList)}
          loading={loading}
          rowKey="id"
          rowSelection={rowSelection}
          pagination={{
            current: listQuery.pageNo,
            pageSize: listQuery.pageSize,
            total,
            onChange: pageChange
          }}
          scroll={{
            x: 'max-content'
          }}
          bordered
        >
          <Column title="序号" dataIndex="id" key="id" align="center" />
          <Column title="主分类名称" dataIndex="cName" key="cName" align="center" />
          <Column title="版本号" dataIndex="cVersion" key="cVersion" align="center" />
          <Column title="分类号" dataIndex="cNo" key="cNo" align="center" />
          <Column title="分类描述" dataIndex="cDescription" key="cDescription" align="center" />
          <Column
            title={formatMessage('tableAction')}
            key="action"
            align="center"
            render={(_text, record: any) => (
              <Space direction="vertical">
                <Space>
                  <Button
                    type="link"
                    onClick={() => {
                      editClassify(record);
                    }}
                  >
                    编辑
                  </Button>
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      deleteItem(record);
                    }}
                  >
                    删除
                  </Button>
                </Space>
                <Space>
                  <Button
                    type="link"
                    onClick={() => {
                      addSameLevelClassify(record.pid);
                    }}
                  >
                    新建同级分类
                  </Button>
                  <Button
                    type="link"
                    onClick={() => {
                      addSubLevelClassify(record.id);
                    }}
                  >
                    新建子分类
                  </Button>
                </Space>
              </Space>
            )}
          />
        </Table>
      </div>
      {useMemo(
        () => (
          <AddItemDialog
            visible={addDialogVisible}
            data={addInfo}
            onClose={() => {
              setAddDialogVisible(false);
            }}
          />
        ),
        [addDialogVisible]
      )}
      {useMemo(
        () => (
          <EditItemDialog
            visible={editDialogVisible}
            data={editInfo}
            onClose={() => {
              setEditDialogVisible(false);
            }}
          />
        ),
        [editDialogVisible]
      )}
    </div>
  );
};

export default ClassifyDetail;
